import { Controller, Get, Post, Put, Del, Inject, Body, Param, Query, Files } from '@midwayjs/decorator';
import { SchoolService } from '../../service/firmware/school.service';
import { Validate } from '@midwayjs/validate';
import { UploadMiddleware, UploadFileInfo } from '@midwayjs/busboy';
import { resBuild } from '@utils/resBuild';
import * as path from 'path';
import { v4 as uuidv4 } from 'uuid';
import * as fs from 'fs';
import { envConfig } from '@config';
@Controller('/school')
export class SchoolController {
  @Inject()
  schoolService: SchoolService;

  // 创建学校
  @Post('/create')
  @Validate() // 触发 DTO 验证
  async create(@Body() body) {
    try {
      const { name, photo, edgroup } = body;
      const school = await this.schoolService.createSchool(name, photo, edgroup.id);
      return resBuild.data(school);
    } catch (error) {
      return resBuild.fail("创建失败！", error.message);
    }
  }

  // 获取所有学校
  @Get('/list')
  async list(@Query() query) {
    try{
      const result = await this.schoolService.getAllSchools(query);
      return resBuild.data(result);
    }catch(err){
      console.log(err)
      return resBuild.fail(err)
    }
    
  }

  // 获取单个学校
  @Get('/:id')
  async getById(@Param('id') id: number) {
    try {
      const school = await this.schoolService.getSchoolById(id);
      if (!school) return resBuild.fail('学校不存在');
      return resBuild.data(school);
    } catch (err) {
      console.log(err)
      return resBuild.fail(err)
    }

  }

  // 更新学校
  @Put('/update/:id')
  @Validate() // 触发 DTO 验证
  async update(@Param('id') id: number, @Body() body) {
    try {
      const { name, photo, edgroup } = body;
      const updatedSchool = await this.schoolService.updateSchool(id, name, photo, edgroup.id);
      if (!updatedSchool) return resBuild.fail("更新失败，学校不存在!");
      return resBuild.data(updatedSchool);
    } catch (error) {
      return resBuild.fail(error.message);
    }
  }

  // 上传图片
  @Post('/upload', { middleware: [UploadMiddleware] })
  async uploadFile(@Files('file') files: UploadFileInfo[]) {
    // 检查上传文件是否存在
    if (!files || files.length === 0) {
      return { code: 500, message: '上传文件不能为空' };
    }
    const file = files[0]; // 取第一个文件
    console.log('file', file)
    // 文件保存路径
    const uploadDir = path.join(__dirname, '../../upload/images');
    // 随机 uuid + 后缀
    let fileName = `${uuidv4()}.${file.data.split('.').pop()}`
    const filePath = path.join(uploadDir, fileName);
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    // // 保存文件
    try {
      // 假设 file.data 是上传的文件的临时路径
      const sourcePath = file.data; // 原文件路径
      const targetPath = filePath; // 目标文件路径
      // 对应服务器路径
      const savePath = `${envConfig.SaveTestPath}/images/${fileName}`
      // 使用 fs.copyFileSync 来复制文件
      fs.copyFileSync(sourcePath, targetPath);
      console.log(`文件已成功复制到: ${targetPath}`);
      return resBuild.data(savePath);
    } catch (error) {
      // throw new Error(`保存文件失败: ${error.message}`);
      return resBuild.fail(`保存文件失败: ${error.message}`);
    }

  }

  // 删除学校
  @Del('/delete/:id')
  async delete(@Param('id') id: number) {
    const deleted = await this.schoolService.deleteSchool(id);
    if (!deleted) return { success: false, message: '删除失败，学校不存在' };
    return { success: true, message: '删除成功' };
  }
}
